from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.core.cache import cache
import uuid
from .models import User
from .serializers import UserRegisterSerializer, UserInfoSerializer

class UserViewSet(viewsets.GenericViewSet):
    queryset = User.objects.all()
    serializer_class = UserInfoSerializer
    
    def get_permissions(self):
        """
        根据不同的action返回不同的权限
        - register和login允许匿名访问
        - 其他接口需要认证
        """
        if self.action in ['register', 'login']:
            return [AllowAny()]
        return [IsAuthenticated()]

    @action(detail=False, methods=['post'])
    def register(self, request):
        """用户注册"""
        serializer = UserRegisterSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()
            return Response({
                'code': 200,
                'message': '注册成功',
                'data': UserInfoSerializer(user).data
            })
        return Response({
            'code': 400,
            'message': '注册失败',
            'data': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

    @action(detail=False, methods=['post'])
    def login(self, request):
        """用户登录
        支持三种方式传参：
        1. JSON格式: {"username": "xxx", "password": "xxx"}
        2. Form表单: username=xxx&password=xxx
        3. Form Data: --form 'username=xxx' --form 'password=xxx'
        """
        # 尝试从不同位置获取登录信息
        username = (
            request.data.get('username') or  # JSON 或 Form Data
            request.POST.get('username') or   # Form 表单
            request.query_params.get('username')  # URL 参数
        )
        password = (
            request.data.get('password') or
            request.POST.get('password') or
            request.query_params.get('password')
        )

        if not username or not password:
            return Response({
                'code': 400,
                'message': '用户名和密码不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(username=username)
            if user.check_password(password):
                token = uuid.uuid4().hex[:15]
                cache.set(f'token:{token}', user.id, timeout=24*60*60)
                
                return Response({
                    'code': 200,
                    'message': '登录成功',
                    'data': {
                        'token': token,
                        'user': UserInfoSerializer(user).data
                    }
                })
            else:
                return Response({
                    'code': 401,
                    'message': '用户名或密码错误'
                }, status=status.HTTP_401_UNAUTHORIZED)
        except User.DoesNotExist:
            return Response({
                'code': 401,
                'message': '用户名或密码错误'
            }, status=status.HTTP_401_UNAUTHORIZED)

    @action(detail=False, methods=['post'])
    def logout(self, request):
        """用户登出"""
        token = request.META.get('HTTP_AUTHORIZATION')
        if token:
            cache.delete(f'token:{token}')
        return Response({
            'code': 200,
            'message': '登出成功'
        })

    @action(detail=False, methods=['get'])
    def info(self, request):
        """获取当前用户信息"""
        return Response({
            'code': 200,
            'data': UserInfoSerializer(request.user).data
        })
